package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Class;
import com.easyattendance.model.Section;
import com.easyattendance.model.Subject;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.SubjectTeacher;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.TimeTable;
import com.easyattendance.services.AddClassService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.TimeTableService;


@WebServlet(name = "AddTimeTableServlet", urlPatterns = { "/AddTimeTableServlet" })
public class AddTimeTableServlet extends HttpServlet {
	

	private static final long serialVersionUID = -3274363467724261996L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		boolean flag = false;
		 
		TimeTableService timeTableService = new TimeTableService();
		AddSectionService addSectionService = new AddSectionService();
		AddSubjectService addSubjectService = new AddSubjectService();
		AddTeacherService addTeacherService = new AddTeacherService();
		AddClassService addClassService = new AddClassService();
		
		TimeTable newTimeTable = new TimeTable();
		
		String day = request.getParameter("daySelected");
		String timeSlot = request.getParameter("timeSlotSelected");
		String subjectId = request.getParameter("subjectSelected");
		String teacherId = request.getParameter("teacherSelected");
		String sectionEmail = request.getParameter("section_id");
		String currentUser = (String) request.getSession().getAttribute("currentUser");
		
		if(day == null|| day.equals("")) {
			request.setAttribute("dayDropdown", "You must select one.");
			flag = true;			
		}
		if(timeSlot == null || timeSlot.equals("")) {
			request.setAttribute("timeslotDropdown", "You must select one.");
			flag = true;
		}
		if(subjectId == null || subjectId.equals("")) {
			request.setAttribute("subjectDropdown", "You must select one.");
			flag = true;
		}
		if(teacherId == null || teacherId.equals("")) {
			request.setAttribute("teacherDropdown", "You must select one.");
			flag = true;
		}
		if(flag == true){
	    	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/setTimeTable.jsp");
	    	rd.forward(request, response);
		}

        boolean res = false;
        
        // Add section foreign key to timetable
        boolean isSectionExists = addSectionService.ifAlreadyExists(sectionEmail);
        Teacher teacher = addTeacherService.getTeacherById(teacherId);
        Class classObj =addClassService.getClassById(addClassService.getClassIdByTeacherId(currentUser));
        
        // Add teacher foreign key to timetable
        boolean isTeacherExists = addTeacherService.ifAlreadyExists(teacher);
        
        // Add semester/year foreign key to timetable
        boolean isClassExists = addClassService.ifAlreadyExists(classObj);
        Subject newSubject = new Subject();
        boolean result = false;
        
        if (isSectionExists) {
        	if(isTeacherExists) {
        		if(isClassExists) {
        			newSubject = addSubjectService.getSubjectBySubjectId(subjectId);
                	boolean isSubjectExists = addSubjectService.ifAlreadyExists(newSubject);
                	if(isSubjectExists) {
                		Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
                		
                		//Parse timeslot to Date
                		
                		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		         Date tempSlot=null;
        				 try {
        					tempSlot = format.parse("2013-10-10 "+timeSlot+":00");
        				} catch (ParseException e) {
        					// TODO Auto-generated catch block
        					e.printStackTrace();
        				}
                        newTimeTable = new TimeTable(day, tempSlot, teacherId, newSubject, teacher, section, classObj);
                        
                        if(! timeTableService.ifAlreadyExists(newTimeTable)) {
                        	
                        	// Increment subject-total-lectures-hours counter in subject-class table
                        	SubjectClass newSubjectClass = addSubjectService.getSubjectClassByIds(subjectId, addClassService.getClassIdByTeacherId(currentUser) );
                        	if(newSubjectClass!=null){
                        		newSubjectClass.setTotal_lecture_hours((newSubjectClass.getTotal_lecture_hours())+1);
                        		addSubjectService.updateSubjectClass(newSubjectClass);
                        	}
                        	else {
                        		SubjectClass subjectClass = new SubjectClass(subjectId, addClassService.getClassIdByTeacherId(currentUser), 1, 0);
                        		addSubjectService.addSubjectClass(subjectClass);
                        	}
                        	
                        	// Increment subject_teacher-total-lectures-hours counter in subject-teacher table
                        	boolean isSubjectTeacherExists = addSubjectService.ifSubTeacherAlreadyExists(subjectId, teacherId);
                        	if(isSubjectTeacherExists) {
                        		SubjectTeacher newSubjectTeacher = addSubjectService.getSubTeacherByIds(subjectId, teacherId);
                        		newSubjectTeacher.setTotal_lecture_status( (newSubjectTeacher.getTotal_lecture_status())+1);
                        		addSubjectService.updateTeacherSubject(newSubjectTeacher);
                        	}
                        	else {
                        		SubjectTeacher newSubjectTeacher = new SubjectTeacher(teacherId, subjectId, 0, 1, teacher, newSubject);
                        		addSubjectService.addTeacherSubject(newSubjectTeacher);
                        	}
                        	
                        	// Add new timetable in timetable table
                        	newTimeTable.setSubject_id(newSubject.getSubject_id());
                        	result = timeTableService.addTimeTable(newTimeTable);
                        }
                        else {
                        	out.println("time table already exists");
                        }
                	}
                	else {
                		out.println("subject does not exists");
                	}
            	}
        		else {
        			out.println("semester/year does not exist.. check your login");
        		}
        	}
            	else {
            		out.println("teacher does not exist.. check your login");
            	}
        }
        else {
        	out.println("section does not exist.. check your login");
        	res = false;
        }
        
        
		if (result) {
			request.setAttribute("addSuccess", "TimeTable added Successful.");
		} else {
			request.setAttribute("addFail", "Not added. Please try again.");
		}
		RequestDispatcher rd = request.getRequestDispatcher("views/teacher/setTimeTable.jsp");
    	rd.forward(request, response);	
    }

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
